// pages/selectZtPosition/selectZtPosition.js
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
let page_js = require("../../utils/pageOptions.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  //autherStatus 0 无授权  1授权成功
  //contentStatus 0 无内容  1有内容
  data: {
    pageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    userInfo: null,
    noLocationUrl: url_js.imgUrl + "no_location.png",
    autherStatus: -1,
    locationObj: {},
    contentStatus: -1,
    lastPositionIndex: -1,
    positionList: [],
    selectedItem: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function (options) {
    //1.解析数据
    let ztdObj = common_js.jsonParse(options.ztdOjb);
    let tempLocationObj = this.data.locationObj;
    let tempUserInfo = user_js.userInfo();
    if (ztdObj.autherStatus == 0) {
      //1.1无经纬度
      this.setData({
        userInfo: tempUserInfo,
        autherStatus: ztdObj.autherStatus
      });
      return;
    }
    //1.2有经纬度
    tempLocationObj.name = ztdObj.name;
    tempLocationObj.address = ztdObj.address;
    tempLocationObj.latitude = ztdObj.latitude;
    tempLocationObj.longitude = ztdObj.longitude;
    //2.同步数据
    this.setData({
      userInfo: tempUserInfo,
      locationObj: tempLocationObj
    });
    //3.请求自提点数据
    this.requestToGetShopList(this.data.pageInfo.curPage, this.data.pageInfo.pageSize, ztdObj.latitude, ztdObj.longitude);
  },

  //请求自提点数据
  requestToGetShopList: function (currPage, pageSize, lat, lon, pullDownRefresh) {
    let data = {
      currPage: currPage,
      lat: lat,
      lon: lon,
      pageSize: pageSize
    };
    api.wxRequest(url_js.shopListUrl, data).then(res => {
      this.handleShopListResponseData(res, currPage, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //设置返回的数据
  handleShopListResponseData: function (res, currPage, pullDownRefresh) {
    //设置数据
    let tmpPositionList = this.data.positionList;
    if (pullDownRefresh) {
      tmpPositionList = [];
    }
    //pageInfo
    let tmpPageInfo = this.data.pageInfo;
    if (res.page.pages <= currPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.result.length > 0) {
      tmpPositionList = tmpPositionList.concat(res.result);
      let tmpIndex = this.data.lastPositionIndex;
      let tmpSelectItem = this.data.selectedItem;
      if (tmpIndex == -1) {
        tmpIndex = this.getMyZtdIndex(tmpPositionList);
        tmpSelectItem = tmpPositionList[tmpIndex];
      }

      this.setData({
        contentStatus: 1,
        pageInfo: tmpPageInfo,
        lastPositionIndex: tmpIndex,
        selectedItem: tmpSelectItem,
        positionList: tmpPositionList
      });
    } else {
      this.setData({
        pageInfo: tmpPageInfo,
        contentStatus: 0
      });
    }
  },

  //获取当前自提点的index
  getMyZtdIndex: function (list) {
    let ztdIndex = -1;
    if (list.length > 0) {
      list.forEach((item, index) => {
        if (item.selected) {
          ztdIndex = index;
        }
      });
    }
    return ztdIndex;
  },

  //打开定位权限
  openPositionAuther: function (e) {
    let isOpenUserLocation = e.detail.isOpenUserLocation;
    // 选择自提点
    if (isOpenUserLocation) {
      let pages = getCurrentPages();
      let prePage = pages[pages.length - 2];
      if (prePage.route.includes('indexSearchShop')) {
        wx.navigateBack({});
      } else {
        wx.redirectTo({
          url: '/pages/indexSearchShop/indexSearchShop',
        })
      }
      // 重新定位
      // this.reLocation();
    }
  },

  //适配2.3.0以下版本
  openAuther: function () {
    //打开用户权限
    wx.openSetting({
      success: res => {
        let isOpenUserLocation = res.authSetting['scope.userLocation'];
        // 选择自提点
        if (isOpenUserLocation) {
          this.reLocation();
        }
      }
    })
  },

  //重新获取定位选取位置
  reLocation: function () {
    //重新定位
    let pages = getCurrentPages();
    let prePage = pages[pages.length - 2];
    prePage.onGw();
    //返回
    wx.navigateBack({});
  },


  //选择其他门店
  openOtherPosition: function () {
    this.openWechatLocation(this.data.locationObj.latitude, this.data.locationObj.longitude);
  },

  //打开微信内置地图
  openWechatLocation: function (latitude, longitude) {
    //1.打开地图选择位置
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: res => {
        //1.设置参数
        let ztdObj = {};
        ztdObj.name = res.name;
        ztdObj.address = res.address;
        ztdObj.latitude = res.latitude;
        ztdObj.longitude = res.longitude;
        this.setData({
          locationObj: ztdObj
        });
        //重新搜索
        this.reloadPageData();
      },
      fail: res => {
        let canceled = res.errMsg.indexOf("cancel") != -1;
        if (canceled) {}
      }
    });
  },


  //reloadData
  reloadPageData: function () {
    //1.reset Pageinfo
    let tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.pageSize = 10;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo
    });

    //2..请求自提点数据
    this.requestToGetShopList(this.data.pageInfo.curPage, this.data.pageInfo.pageSize, this.data.locationObj.latitude, this.data.locationObj.longitude);
  },

  //获取用户信息
  onGetUserInfo: function (res) {
    let denied = res.detail.errMsg.indexOf("auth deny") != -1;
    if (denied) return;
    this.requestToSelectShop(res.detail.userInfo);

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.selectZtPositionSelect);
  },

  //选择自提点，将刚才的自提点信息返回
  requestToSelectShop: function (userInfo) {
    let tmpSelectItem = this.data.selectedItem;
    let data = {
      code: this.data.userInfo.code,
      shopId: tmpSelectItem.id,
      geoLat: this.data.locationObj.latitude,
      geoLon: this.data.locationObj.longitude
    }
    api.wxRequest(url_js.shopSelectShopUrl, data).then(res => {
      this.handleSelectShopData(res, userInfo);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理选中自提点返回的数据
  handleSelectShopData: function (res, userInfo) {
    //2.保存当前用户自提点
    let tempUserInfo = user_js.userInfo();
    //0 购物
    tempUserInfo.role = 1;
    tempUserInfo.wxUserInfo = userInfo;
    tempUserInfo.ztd = this.data.selectedItem;
    user_js.saveUserInfo(tempUserInfo);
    //3.根据shareType不同，跳转到不同的页面
    let tmpPageOptions = page_js.pageOptionsInfo();
    if (!tmpPageOptions) {
      wx.switchTab({
        url: '../index/index'
      });
    } else {
      wx.reLaunch({
        url: tmpPageOptions.url + tmpPageOptions.param
      });
    }
    if (tmpPageOptions) {
      page_js.clearPageOptionsInfo();
    }
  },

  //我选好了
  onSure: function () {
    //1.没有选择
    if (!this.data.selectedItem || !this.data.selectedItem.selected) {
      common_js.showToast('请选择自提点!');
      return;
    }
  },

  //点击自提点
  onItem: function (e) {
    let index = parseInt(e.currentTarget.dataset.index);
    //1.重置上一个自提点
    if (this.data.lastPositionIndex != -1 && this.data.lastPositionIndex != index) {
      let lastItem = this.data.positionList[this.data.lastPositionIndex];
      if (lastItem.selected) {
        lastItem.selected = !lastItem.selected;
        this.data.positionList.splice(this.data.lastPositionIndex, 1, lastItem);
      }
    }

    //2.选择当前自提点
    let item = this.data.positionList[index];
    item.selected = !item.selected;
    this.data.positionList.splice(index, 1, item);
    this.setData({
      lastPositionIndex: index,
      selectedItem: item,
      positionList: this.data.positionList
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //check 
    if (this.data.contentStatus != 1) {
      wx.stopPullDownRefresh();
      return
    }
    //2.reset data
    let tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo
    });
    //3.request
    this.requestToGetShopList(tmpPageInfo.curPage, tmpPageInfo.pageSize, this.data.locationObj.latitude, this.data.locationObj.longitude, true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pageInfo.noMore) return;
    //1. request
    this.requestToGetShopList(this.data.pageInfo.curPage, this.data.pageInfo.pageSize, this.data.locationObj.latitude, this.data.locationObj.longitude);
  },
})